package com.gensdai.leliang.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.gensdai.leliang.R;
import com.gensdai.leliang.base.BaseActivityNoAbs;
import com.gensdai.leliang.dialog.Upload;
import com.gensdai.leliang.entity.UserNameBean;
import com.gensdai.leliang.json_base.json_base;
import com.gensdai.leliang.remoteInterface.ApiService;
import com.trello.rxlifecycle2.android.ActivityEvent;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Administrator on 2017/6/1.
 */

public class my_wallet extends BaseActivityNoAbs implements View.OnClickListener {

    @BindView(R.id.ui_title)
    TextView uiTitle; //标题
    @BindView(R.id.right_tv)
    TextView rightTv; //余额明细
    @BindView(R.id.back)
    LinearLayout back;//返回
    @BindView(R.id.recharge)
    TextView recharge;//充值
    @BindView(R.id.extract)
    TextView extract; //提现
    @BindView(R.id.user_all_money)
    TextView userAllMoney; // 总资产
    @BindView(R.id.today_money)
    TextView todayMoney; // 成长金总额
    @BindView(R.id.grouthjin)
    TextView grouthjin; // 可用成长金
    @BindView(R.id.grouthbei)
    TextView grouthbei;  // 成长贝总额
    @BindView(R.id.grouthbeibalance)
    TextView grouthbeibalance; //可用成长贝
    @BindView(R.id.get_deal)
    LinearLayout getDeal;//成长贝获得记录
    @BindView(R.id.grouthjin_deal)
    LinearLayout grouthjinDeal;//成长金获取记录
    @BindView(R.id.grantdeal)
    LinearLayout grantdeal; // 成长贝发放记录
    @BindView(R.id.use_bei)
    LinearLayout useBei;// 成长贝使用记录
    @BindView(R.id.invite_friend_deal)
    LinearLayout inviteFriendDeal; // 邀请好友记录
    @BindView(R.id.zcjs_img)
    ImageView zcjsImg;
    @BindView(R.id.czj_js)
    ImageView czjJs;
    @BindView(R.id.czjjs_img)
    ImageView czjjsImg;
    @BindView(R.id.czb_js)
    ImageView czbJs;
    @BindView(R.id.czbjs_img)
    ImageView czbjsImg;

    private Upload up;
    private static final int GET_DATA = 1;
    UserNameBean user;
    SharedPreferences share;
    SharedPreferences.Editor ed;

    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case GET_DATA:
                    up.dismiss();
                    try {
                        if (new json_base().GOOD((String) msg.obj)) {
                            user = (UserNameBean) new json_base().jsonWallet(new JSONObject((String) msg.obj));
                            setData();
                        } else {
                            Toast.makeText(my_wallet.this, "网络错误", Toast.LENGTH_SHORT).show();
//                            todayMoney.setText(String.format(getString(R.string.keyongyue), share.getString("money", "0")));
//                            userAllMoney.setText(String.format(getString(R.string.hhh), share.getString("money", "0")));
//                            grouthjin.setText(String.format(getString(R.string.leijichengzhangjin), "0"));
//                            grouthbei.setText(String.format(getString(R.string.leijichengzhangbei), "0"));
                            todayMoney.setText(String.format(getString(R.string.use_monry), share.getString("money", "0")));
                            userAllMoney.setText(String.format(getString(R.string.hhh), share.getString("money", "0")));
                            grouthjin.setText(String.format(getString(R.string.add_up_gold), "0"));
                            grouthbei.setText(String.format(getString(R.string.add_up_shell), "0"));
                            grouthbeibalance.setText(String.format(getString(R.string.add_up_balance), "0"));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                default:

                    up.dismiss();
                    break;
            }
        }

        ;
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_wallet);
        ButterKnife.bind(this);
        init();
        todayMoney.setText(String.format(getString(R.string.use_monry), share.getString("money", "0")));
        userAllMoney.setText(String.format(getString(R.string.hhh), share.getString("money", "0")));
        grouthjin.setText(String.format(getString(R.string.add_up_gold), "0"));
        grouthbei.setText(String.format(getString(R.string.add_up_shell), "0"));
        grouthbeibalance.setText(String.format(getString(R.string.add_up_balance), "0"));
    }

    @Override
    protected void onStart() {
        super.onStart();
        QueryAccountRequest2Str();
    }

    /**
     * 初始化
     */
    private void init() {
        share = getSharedPreferences("User", MODE_PRIVATE);
        ed = share.edit();
        uiTitle.setText(getString(R.string.my_money_package));
        up = new Upload(this);
        rightTv.setVisibility(View.VISIBLE);
        back.setOnClickListener(this);
        rightTv.setOnClickListener(this);
        recharge.setOnClickListener(this);
        extract.setOnClickListener(this);
        getDeal.setOnClickListener(this);
        grouthjinDeal.setOnClickListener(this);
        grantdeal.setOnClickListener(this);
        useBei.setOnClickListener(this);
        inviteFriendDeal.setOnClickListener(this);

        userAllMoney.setOnClickListener(this);
        czjJs.setOnClickListener(this);
        czbJs.setOnClickListener(this);

    }

    private void setData() {
//        todayMoney.setText(String.format(getString(R.string.keyongyue), user.getTotalAmount()));
//        userAllMoney.setText(String.format(getString(R.string.hhh), user.getAvailableAmount()));
//        grouthjin.setText(String.format(getString(R.string.leijichengzhangjin), user.getGrouthJin()));
//        grouthbei.setText(String.format(getString(R.string.leijichengzhangbei), user.getGrouthBei()));

        todayMoney.setText(String.format(getString(R.string.use_monry), user.getGrouthJin()));
        userAllMoney.setText(String.format(getString(R.string.hhh), user.getTotalAmount()));
        grouthjin.setText(String.format(getString(R.string.add_up_gold), user.getGrouthJinBlance()));
        grouthbei.setText(String.format(getString(R.string.add_up_shell), user.getGrouthBei()));
        grouthbeibalance.setText(String.format(getString(R.string.add_up_balance), user.getGrouthBeiBlance()));

        ed.putString("money", user.getGrouthJinBlance());
        ed.commit();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.right_tv:
                Toast.makeText(this, "功能正在开发中，尽请关注哦！~", Toast.LENGTH_SHORT).show();
                break;
            case R.id.back:
                this.finish();
                break;
            case R.id.recharge:
                Intent go_recharge = new Intent(this, Recharge.class);
                go_recharge.putExtra("money", user.getGrouthJinBlance());
                startActivity(go_recharge);
                break;
            case R.id.extract:
                Intent go_extract = new Intent(this, Enchashment.class);
                go_extract.putExtra("money", user.getGrouthJinBlance());
                startActivity(go_extract);
                break;
            case R.id.get_deal:
                Intent go_getDeal = new Intent(this, Get_deal.class);
                startActivity(go_getDeal);
                break;
            case R.id.grouthjin_deal:
                Intent go_grouthjin_deal = new Intent(this, Get_Griytg_Gold.class);
                startActivity(go_grouthjin_deal);
                break;
            case R.id.grantdeal:
                Intent go_grantdeal = new Intent(this, Grant_Bei_Deal.class);
                startActivity(go_grantdeal);
                break;
            case R.id.use_bei:
                Intent go_use_bei = new Intent(this, Use_Bei_Deal.class);
                startActivity(go_use_bei);
                break;
            case R.id.invite_friend_deal:
//                Toast.makeText(this, "功能正在开发中，尽请关注哦！~", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(this, invite_friend_deal.class);
                intent.putExtra("flag", "2");
                startActivity(intent);
                finish();
                break;
            case R.id.user_all_money:
                if (zcjsImg.getVisibility() == View.INVISIBLE) {
                    zcjsImg.setVisibility(View.VISIBLE);
                }else{
                    zcjsImg.setVisibility(View.INVISIBLE);
                }
                break;
            case R.id.czb_js:
                if (czbjsImg.getVisibility() == View.GONE) {
                    czbjsImg.setVisibility(View.VISIBLE);
                }else{
                    czbjsImg.setVisibility(View.GONE);
                }
                break;
            case R.id.czj_js:
                if (czjjsImg.getVisibility() == View.GONE) {
                    czjjsImg.setVisibility(View.VISIBLE);
                }else{
                    czjjsImg.setVisibility(View.GONE);
                }
                break;
            default:
                break;
        }
    }


    private void QueryAccountRequest2Str() {
        Map<String, String> loginParams = new HashMap<>();
        loginParams.put("userno", getSharedPreferences("User", MODE_PRIVATE).getString("userno", ""));
        loginParams.put("token", getSharedPreferences("User", MODE_PRIVATE).getString("token", ""));
        toStr(loginParams);
    }

    /**
     * 获取我的錢包信息
     */
    private void toStr(Map<String, String> data) {
        up.show();
        ApiService.getInstance().QueryAccountRequest2Str(data)
                //涉及到IO操作
                .subscribeOn(Schedulers.io())
                .compose(this.<String>bindUntilEvent(ActivityEvent.DESTROY)) //跟生命周期绑定一起
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //开始监听前的处理，一般用于显示dialog什么的
////                        if (hud != null) {
////                            hud.show();
////                        }

                        Log.d("accept", "accept");
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        //可以取消订阅
                        //还可以判断是否处于取消状态
                        //boolean b=d.isDisposed();

                        Log.d("onSubscribe", "onSubscribe");
                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        //处理得到的数据
                        Log.e("quick_login", s);
                        Message msg = new Message();
                        msg.what = GET_DATA;
                        msg.obj = s;
                        mHandler.sendMessage(msg);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        up.dismiss();
                        //异常处理
                    }

                    @Override
                    public void onComplete() {
                        //监听完毕后的处理
                        Log.d("onComplete", "onComplete");
                    }
                });
    }


}
